<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Shop as ShopModel;
use app\admin\model\User;
use app\admin\model\Admin;
use app\admin\model\ShopPriceLog;
use app\admin\model\DistributeTask;
use app\admin\model\AuthGroupAccess;
use fast\Random;
use think\Db;
use think\Exception;
use think\Session;

/**
 * 商户管理
 *
 * @icon   fa fa-list
 */
class Shop extends Backend
{

    protected $model = null;
    protected $group_id = null;
    protected $admin = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ShopModel();
        $admin = Session::get('admin');
        $group_id = db('auth_group_access')->where(['uid'=>$admin['id']])->value('group_id');
        $this->group_id = $group_id;
        $this->admin = $admin;
        $this->assignconfig('group_id', $group_id);
        $this->view->assign('group_id', $group_id);
    }


     /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $where1 = ['name'=>['neq','']];
            if($this->group_id == 6){
                $shop = ShopModel::where(['admin_id'=>$this->admin['id']])->find();
                if($shop){
                    $where1 = ['id'=>$shop['id']];
                }
            }

            $list = $this->model
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                if($v['user_id']){
                    $v['nickname'] = User::where(['id'=>$v['user_id']])->value('nickname');
                }else{
                    $v['nickname'] = '后台添加';
                }
                //查询用户总充值金额
                $v['sum_recharge'] = ShopPriceLog::where(['shop_id'=>$v['id'],'type'=>2])->sum('price');
                //查询用户支出总金额
                $v['shop_sum_expend'] = ShopPriceLog::where(['shop_id'=>$v['id'],'type'=>['in',[1,3]]])->sum('price');
                //苏拉支出总金额
                $v['sl_sum_expend'] = DistributeTask::where(['shop_id'=>$v['id'],'status'=>3])->sum('price')*-1;
                //总利润
                $v['sum_profit'] = bcsub($v['shop_sum_expend']*-1 , $v['sl_sum_expend']*-1,2);
                //查询发了多少个帖子
                $v['success_num'] = DistributeTask::where(['shop_id'=>$v['id']])->count();
                $v['error_num'] = DistributeTask::where(['shop_id'=>$v['id'],'status'=>-2])->count();

                if($v['balance']){
                    $v['shuliang'] = $v['balance'];
                }elseif($v['monthly_num'] || $v['thirdpartnar_num'] || $v['enemy_num']){
                    $v['shuliang'] = $v['monthly_num']+$v['thirdpartnar_num']+$v['enemy_num'];
                }
                
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    //帖子发完清空余额
    public function empty_balance($id = null)
    {
        $shop = ShopModel::where(['id'=>$id])->find();
        if(!$shop){
            $this->error('商户错误');
        }
        ShopModel::where(['id'=>$id])->update(['balance'=>0]);

        $arr = [
            'user_id'=>$shop['user_id'],
            'shop_id'=>$shop['id'],
            'price'=>$shop['balance']*-1,
            'type'=>1,
            'add_time'=>time(),
            'admin_id'=>$this->admin['id'],
            'remark'=>'帖子发完清空余额'
        ];

        if($shop['monthly_num']){
            $arr['consumption_type'] = '4';
        }elseif($shop['thirdpartnar_num']){
            $arr['consumption_type'] = '3';
        }elseif($shop['enemy_num']){
            $arr['consumption_type'] = '2';
        }elseif($shop['comment_num']){
            $arr['consumption_type'] = '5';
        }else{
            $arr['consumption_type'] = '1';
        }


        ShopPriceLog::insert($arr);
        $this->success('操作成功');
    }


    
    //自运营账号手动扣款
    public function manual_withhold($id = null)
    {
        $shop = ShopModel::where(['id'=>$id])->find();
        if($shop['balance'] < $shop['fixed_price']){
            $this->error('账号余额不足');
        }
        add_shop_balance_log($shop['id'],$shop['fixed_price'],$shop['balance'],1);
        ShopModel::where(['id'=>$shop['id']])->update(['balance'=>$shop['balance'] - $shop['fixed_price']]);
        $this->success('操作成功');
    }

    /**
     * 审核操作
     *
     * @return string
     * @throws \think\Exception
     */
    public function update_status($id = null)
    {
        $status = $this->request->request('status');
        $remark = $this->request->request('remark','');
        $result = false;
        Db::startTrans();
        try {
            if($status == 1){
                $row = $this->model->where(['id'=>$id])->find();
                //User::where(['id'=>$row['user_id']])->update(['is_shop'=>1]);

                //创建后台admin账号
                $salt = Random::alnum();
                //创建admin账号
                $admin = [
                    'username'=>$row['name'],
                    'nickname'=>$row['name'],
                    'salt'=>$salt,
                    'password'=>md5(md5(123456) . $salt),
                    'avatar'=>'/assets/img/avatar.png',
                ];
                $admin_id = Admin::insertGetId($admin);
                AuthGroupAccess::insert(['uid'=>$admin_id,'group_id'=>6]);
                $update = ['status'=>$status,'remark'=>$remark,'admin_id'=>$admin_id];
            }else{
                $update = ['status'=>$status,'remark'=>$remark];
            }
            $result = $this->model->where(['id'=>$id])->update($update);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        //查询商户名称
        $info = $this->model->where(['name'=>$params['name'],'status'=>['neq',-1]])->find();
        if($info){
            $this->error('该商户名已被注册,请重新输入');
        }

        //判断固定价格是否存在
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $section_price = '';
            if(!empty($params['award'])){
                $award = [];
                $price = [];
                foreach ($params['award'] as $k=>$v) {
                    if($v){
                        $award[] = explode('-',$v);
                        $price[] = $params['price'][$k];
                    }
                }
                $section_price = [
                    'award'=>$award,
                    'price'=>$price,
                    
                ];
            }
            $salt = Random::alnum();
            //创建admin账号
            $admin = [
                'username'=>$params['name'],
                'nickname'=>$params['name'],
                'salt'=>$salt,
                'password'=>md5(md5(123456) . $salt),
                'avatar'=>'/assets/img/avatar.png',
            ];
            $admin_id = Admin::insertGetId($admin);
            AuthGroupAccess::insert(['uid'=>$admin_id,'group_id'=>6]);
            $arr = [
                'name'=>$params['name'],
                'fixed_price'=>!empty($params['fixed_price']) ? $params['fixed_price'] : 0,
                'section_price'=>$section_price ? json_encode($section_price) : '',
                'add_time'=>time(),
                'admin_id'=>$admin_id,
                'status'=>1
            ];
            $result = $this->model->insert($arr);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }



    //资金管理
    public function shop_fund($ids = '')
    {
        $ids = $ids ? $ids : $this->request->post("ids",'');
    
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //查询该用户是否是商家
            if($this->group_id == 6){
                $shopwhere = ['name'=>$this->admin['nickname'],'status'=>1];
                $shop = ShopModel::where($shopwhere)->find();
                $where1 = ['shop_id'=>$shop['id']];
            }else{
                $shopwhere = ['status'=>1];
                if($ids && $ids != 'null '){
                    $where1 = ['shop_id'=>$ids];
                }else{
                    $where1 = [];
                }
                $shop = ShopModel::where($shopwhere)->select();
            }
            if($shop){
                
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $list = ShopPriceLog::where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->paginate($limit);
                foreach ($list as &$v) {
                    $v['shop_name'] =  ShopModel::where(['id'=>$v['shop_id']])->value('name');
                    if($v['user_id']){
                        $v['nickname'] = User::where(['id'=>$v['user_id']])->value('nickname');
                    }else{
                        $v['nickname'] = '后台添加';
                    }
                    //状态  1支出   2充值   3解冻  4冻结
                    if($v['type'] == 1 && $v['is_freeze'] == 1){
                        $v['type'] = 4;
                    }
                    $v['is_houtai'] = 0;
                    if($v['img']){
                        $v['is_houtai'] = 1;
                    }
                }
                $result = array("total" => $list->total(), "rows" => $list->items());
            }
            if(!empty($result)){
                return json($result);
            }else{
                $result = array("total" => 0, "rows" => []);
                return json($result);
            }

            
        }
        return $this->view->fetch();
    }
     
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function fund_add()
    {
        if (false === $this->request->isPost()) {

            $shop_arr = ShopModel::where(['status'=>1])->select();
            $this->view->assign('shop_arr', $shop_arr);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if($this->admin['id'] != 1){
            $this->error('无操作权限,请联系管理员');
        }

        //判断固定价格是否存在
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $shop = ShopModel::where(['id'=>$params['shop_id'],'status'=>1])->find();
            if(!$shop){
                $this->error('商户信息错误');
            }
            $arr = [
                'user_id'=>$shop['user_id'],
                'shop_id'=>$shop['id'],
                'price'=>$params['price'],
                'type'=>2,
                'add_time'=>time(),
                'admin_id'=>$this->admin['id'],
                'img'=>$params['img']
            ];
            $result = ShopPriceLog::insert($arr);
            if($result){
                ShopModel::where(['id'=>$shop['id']])->update(['balance'=>$shop['balance'] + $params['price']]);
                add_shop_balance_log($shop['id'],$params['price'],$shop['balance'],2);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }

    //代理商列表
    public function agent_list(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = User::where($where)
                ->where(['is_shop'=>1,'is_agent'=>['>',0]])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $v['agent_text'] =  json_decode($v['agent_text'],true);
                
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function setagentStatus(){
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            Db::startTrans();
            try {
                $result = User::where(['id'=>$data['id']])->update(['is_agent'=>$data['is_agent']]);
                if ($result) {
                    Db::commit();
                    $this->success();
                } else {
                    Db::commit();
                    $this->error('操作失败');
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


            
        }
    }
   
    


}